package genetic;

public class SBXCrossover implements Crossover {
	double contiguity;
	
	public SBXCrossover(double contiguity) {
		this.contiguity = contiguity;
	}
	
	//SBX
	@Override
	public void crossover(Individual a, Individual b) {
		for (int i = 0; i < a.x.length; i++) {
			double u = Math.random();
			double beta = 0;
			if (u < 0.5) // if u is smaller than 0.5 perform a contracting crossover
				beta = Math.pow(2*u, 1.0/(contiguity+1));
			else if (u > 0.5)
				beta = Math.pow(0.5 / (1.0 - u), 1.0 / (contiguity + 1));
			else
				beta = 1;
			double delta = beta * 0.5 * Math.abs(a.x[i] - b.x[i]);
			double avg = (a.x[i] + b.x[i]) / 2.0;
			if (Math.random() < 0.5)
				delta = -delta;
			a.x[i] = avg - delta;
			b.x[i] = avg + delta;
		}
		a.normalize();
		b.normalize();
	}
}
